import threading

from flask import *
import os
from src import utils, log, mysql_db as db
from src.model.model import SyncStatus
from src import utils
from src.service.file_compare_service import compare_exec
from src.common.files import Files

blueprint = Blueprint('dataTools', __name__)


@blueprint.route('/api/dataTools/fileCompare', methods=['POST'])
def file_compare():
    try:
        data_dict = json.loads(request.get_data(as_text=True))
        # 解析参数
        columns = data_dict['columns']
        file_list = data_dict['filesName']
        # 获取该需要对比的两个文件
        upload_path = utils.get_upload_path()
        file1 = os.path.join(upload_path + file_list[0])
        file2 = os.path.join(upload_path + file_list[1])
        # 设置需要写入的文件
        uuid = utils.get_uuid()
        result_path = utils.get_result_path()
        utils.is_exists(result_path)
        output_file = os.path.join(result_path, uuid + '.xlsx')
        now_time = utils.get_YmdHMS()
        db_data = SyncStatus(dt=utils.get_Ymd(), uuid=uuid, status=0, create_time=now_time, update_time=now_time)
        db.session.add(db_data)
        db.session.commit()
        threading.Thread(target=compare_exec, args=(uuid, file1, file2, columns, output_file)).start()
        return jsonify({'code': 200, 'message': '服务端处理中...请稍后....', 'success': True, 'data': uuid})
    except Exception as e:
        log.error(e)
        return jsonify({'code': -1, 'message': '服务端异常', 'success': False, 'data': None})


@blueprint.route('/api/file/query', methods=['POST'])
def file_compare_status():
    try:
        data_dict = json.loads(request.get_data(as_text=True))
        file_name = data_dict['fileName']
        db_data = db.session.query(SyncStatus).filter(SyncStatus.uuid == file_name).first()
        if db_data and db_data.__dict__['status'] == 1:
            return jsonify({'errCode': '', 'errMsg': '', 'success': True, 'data': {'status': 1}})
        else:
            return jsonify({'errCode': '', 'errMsg': '', 'success': True, 'data': {'status': 0}})
    except Exception as e:
        log.error(e)
        return jsonify({'code': -1, 'message': '服务端异常', 'success': False, 'data': None})


@blueprint.route('/api/file/getTableData', methods=['POST'])
def getTableData():
    data_dict = json.loads(request.get_data(as_text=True))
    file_name = data_dict['fileName']
    sheetNo = data_dict['sheetNo']
    pageNum = data_dict['pageNum']
    pageSize = data_dict['pageSize']

    result_path = utils.get_result_path()
    download_path = os.path.join(result_path, file_name + '.xlsx')
    if os.path.exists(download_path):
        columns, total, data_list = Files.read_excel(path=download_path, sheet_no=sheetNo, page_num=pageNum, page_size=pageSize)
        return jsonify({'errCode': '', 'success': True, 'data': {'total': total, 'tableColumn': columns, 'tableData': data_list}})